package org.darkforest.ucenter.service.impl;

import org.darkforest.dao.mapper.AreaMapper;
import org.darkforest.dao.redis.AreaRedisDao;
import org.darkforest.model.Area;
import org.darkforest.ucenter.service.AreaRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by valentina on 15/3/15.
 */
@Service
public class AreaRedisServiceImpl implements AreaRedisService {
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private AreaRedisDao redisDao;


    @Override
    public List<Area> getAreaList(String parentAreaId) {
        List<Area> areaList = new ArrayList<Area>();
        if(parentAreaId==null){
            areaList = redisDao.getAreaList("area_list");
            if(areaList==null || areaList.size()==0){
                areaList = areaMapper.getAreaListByParentId(0);
                redisDao.addAreaList("area_list",areaList);
            }
        }else{
            areaList = redisDao.getAreaList("area_list_"+parentAreaId);
            if(areaList==null || areaList.size()==0){
                areaList = areaMapper.getAreaListByParentId(Integer.parseInt(parentAreaId));
                redisDao.addAreaList("area_list_"+parentAreaId,areaList);
            }
        }
        return areaList;
    }

    @Override
    public void initAreaListToRedis() {
        List<Area> parentArea = areaMapper.getAreaListByParentId(0);            //获取一级区域列表
        redisDao.addAreaList("area_list",parentArea);
        for(Area area : parentArea){
            List<Area> areas = areaMapper.getAreaListByParentId(area.getAreaId());      //获取二级区域列表
            redisDao.addAreaList("area_list_"+area.getAreaId(),areas);
            //二级区域不为空时获取三级区域并存储
            if(areas!=null && areas.size()>0){
                for (Area subArea : areas){
                    List<Area> threeArea = areaMapper.getAreaListByParentId(subArea.getAreaId());
                    redisDao.addAreaList("area_list_"+subArea.getAreaId(),threeArea);
                }
            }
        }
    }
}
